<template>
  <div class="add-btn">
    <el-button type="text" size="small" @click="openDialog">新增</el-button>
    <el-dialog title="新增信息来源" :visible.sync="dialogVisible" @close="closeDialog" :lock-scroll="true" 
      :close-on-press-escape="false" :close-on-click-modal="false" center top="40px">
      <el-form ref="form" :model="form">
        <el-form-item label="信息来源名称">
          <el-input v-model="form.sourceName" placeholder="请输入信息来源名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="saveSource">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      form: {
        sourceName: "",
      },
    };
  },
  methods: {
    openDialog() {
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
      this.form.sourceName = "";
    },
    saveSource() {
      if (this.form.sourceName) {
        this.saveToServer(this.form.sourceName);
        this.closeDialog();
      } else {
        this.$message.error("信息来源名称不能为空");
      }
    },
    async saveToServer(sourceName) {
      const { code, data } = await this.$fetch.post(
        "/api/article/classIfy/create",
        {
          value: sourceName,
        }
      );
      if (code === 0) {
        this.$message.success("新增信息来源成功");
        this.$emit("update", data);
      }
    },
  },
};
</script>

<style scoped>
.add-btn {
  margin-left: 4px;
  margin-right: 4px;
}
</style>
